/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.security;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.RequestRejectedHandler;

import com.zhg2yqq.wheels.cache.service.ICacheService;
import com.zhg2yqq.wheels.security.handler.AnonymousAuthenticationEntryPoint;
import com.zhg2yqq.wheels.security.handler.CustomRequestRejectedHandler;
import com.zhg2yqq.wheels.security.handler.LoginFailureHandler;
import com.zhg2yqq.wheels.security.handler.LoginSuccessHandler;
import com.zhg2yqq.wheels.security.handler.LoginUserAccessDeniedHandler;
import com.zhg2yqq.wheels.security.handler.LogoutSuccessHandler;
import com.zhg2yqq.wheels.security.multi.CustomAuthenticationProperties;
import com.zhg2yqq.wheels.security.multi.CustomAuthenticationProvider;
import com.zhg2yqq.wheels.security.multi.CustomFormLoginConfigurer;
import com.zhg2yqq.wheels.security.multi.EmailAuthenticationTokenHandler;
import com.zhg2yqq.wheels.security.multi.NormalAuthenticationTokenHandler;
import com.zhg2yqq.wheels.security.multi.NormalWithCodeAuthenticationTokenHandler;
import com.zhg2yqq.wheels.security.multi.PhoneAuthenticationTokenHandler;
import com.zhg2yqq.wheels.security.multi.TokenCheckHelper;

/**
 * @author zhg2yqq, 2022年11月28日
 * @version zhg2yqq v1.0
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(CustomeSecurityProperties.class)
public class SecurityConfiguration {
    @Bean
    @ConditionalOnMissingBean
    CustomAuthenticationProperties customAuthenticationProperties() {
        return new CustomAuthenticationProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    ISecurityRepository securityRepository(ICacheService cacheService,
                                           ISecurityEventHook securityEventHook,
                                           CustomeSecurityProperties securityProperties) {
        return new SecurityRepositoryHelper(cacheService, securityEventHook, securityProperties);
    }

    /**
     * 自定义登录身份处理
     *
     * @param userDetailsService
     * @param passwordEncoder
     */
    @Bean
    @ConditionalOnMissingBean
    CustomAuthenticationProvider customAuthenticationProvider(UserDetailsService userDetailsService,
                                                              PasswordEncoder passwordEncoder,
                                                              ISecurityRepository securityRepository,
                                                              ISecurityService securityService) {
        TokenCheckHelper checkHelper = new TokenCheckHelper();
        checkHelper.setPasswordEncoder(passwordEncoder);
        checkHelper.setSecurityRepository(securityRepository);
        CustomAuthenticationProvider provider = new CustomAuthenticationProvider(userDetailsService,
                checkHelper);
        provider.setSecurityService(securityService);
        return provider;
    }

    @Bean
    @ConditionalOnMissingBean(ISecurityService.class)
    public ISecurityService securityService() {
        throw new NoSuchBeanDefinitionException(ISecurityService.class,
                "请先实现权限必要ISecurityService接口并装配到Spring容器中");
    }

    @Bean
    @ConditionalOnMissingBean(UserDetailsService.class)
    public UserDetailsService defaultUserDetailsService(ISecurityService securityService,
                                                        CustomeSecurityProperties securityProperties) {
        return new DefaultUserDetailsService(securityService, securityProperties);
    }

    @Bean
    @ConditionalOnMissingBean(ISecurityEventHook.class)
    public ISecurityEventHook securityEventHook() {
        return new ISecurityEventHook() {
        };
    }

    @Bean
    public RequestRejectedHandler requestRejectedHandler() {
        return new CustomRequestRejectedHandler();
    }

    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @ConditionalOnMissingBean(SecurityFilterChain.class)
    public SecurityFilterChain securityAjaxFilterChain(HttpSecurity http,
                                                       CustomeSecurityProperties securityProperties,
                                                       ISecurityEventHook eventHook,
                                                       ISecurityRepository securityRepository,
                                                       CustomAuthenticationProperties properties)
            throws Exception {
        http.addFilterBefore(new JwtAuthenticationFilter(securityRepository), UsernamePasswordAuthenticationFilter.class)
                // 关闭csrf
                .csrf().disable().cors().and().headers().frameOptions().disable().and().exceptionHandling()
                .authenticationEntryPoint(new AnonymousAuthenticationEntryPoint(eventHook))// 匿名用户访问无权限资源时的异常处理
                .accessDeniedHandler(new LoginUserAccessDeniedHandler(eventHook))// 登录用户没有权限访问资源
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 登入
        CustomFormLoginConfigurer<HttpSecurity> formLoginConfigurer = http
                .apply(new CustomFormLoginConfigurer<HttpSecurity>(properties))
                .addTokenFactory(
                        new NormalAuthenticationTokenHandler.NormalAuthenticationTokenFactory())
                .addTokenFactory(
                        new NormalWithCodeAuthenticationTokenHandler.NormalWithCodeAuthenticationTokenFactory())
                .addTokenFactory(
                        new EmailAuthenticationTokenHandler.EmailAuthenticationTokenFactory())
                .addTokenFactory(
                        new PhoneAuthenticationTokenHandler.PhoneAuthenticationTokenFactory())
                .loginProcessingUrl(securityProperties.getLoginUrl());
        if (securityProperties.getLoginAfterUrl() != null) {
            formLoginConfigurer.defaultSuccessUrl(securityProperties.getLoginAfterUrl());
        }
        formLoginConfigurer.successHandler(new LoginSuccessHandler(securityProperties, securityRepository, eventHook));// 登录成功处理逻辑
        formLoginConfigurer.failureHandler(new LoginFailureHandler(eventHook));// 登录失败处理逻辑
        formLoginConfigurer.permitAll();// 允许所有用户

        // 登出
        LogoutConfigurer<HttpSecurity> logoutConfigurer = http.logout()
                .logoutUrl(securityProperties.getLogoutUrl());
        logoutConfigurer.logoutSuccessHandler(new LogoutSuccessHandler(securityProperties, securityRepository, eventHook));// 登出成功处理逻辑
        logoutConfigurer.deleteCookies(securityProperties.getTokenName()).permitAll();// 允许所有用户

        // 需要鉴权认证
        http.authorizeRequests()
                // 放行接口
                .anyRequest().permitAll();

        return http.build();
    }
}
